#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>

#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <signal.h>

#define N 32
#define M 256

enum{
	L = 0x1,
	C,
};

typedef struct{
	int type ;//消息类型
	char name[N];
	char text[M];//消息正文
}MSG;

#define LEN sizeof(MSG)

int main(int argc,const char *argv[]){
	int sockfd;
	struct sockaddr_in serveraddr;
	MSG msg;
	pid_t pid;
	socklen_t len = sizeof(struct sockaddr);
	
	if (argc != 3 ){
		printf("user :%s is port ", argv[0]);
		return -1;
	}
	
	//创建socket
	sockfd = socket (AF_INET,SOCK_DGRAM, 0);
	if(sockfd < 0){
		perror("socket err");
		exit(-1);
	}
		
		//指定服务器地址
		bzero(&serveraddr,len);
		serveraddr.sin_family = AF_INET;
		serveraddr.sin_port = htons(atoi(argv[2]));
		serveraddr.sin_addr.s_addr = inet_addr(argv[1]);
		
		//输入姓名，并发给服务器登录信息
		puts("=========client login=============");
		msg.type = L;
		printf("input name:");
		gets(msg.name);
		sendto(sockfd,&msg,LEN,0,(struct sockaddr *)&serveraddr,len);
		
		//fork --子进程发送，父进程接收
		pid = fork();
		if(pid < 0){
			perror("fork err");
			exit (-1);
		}else if(pid == 0){
			while(1){
				gets(msg.text);
				msg.type = C;
				sendto (sockfd,&msg,LEN,0,(struct sockaddr *)&serveraddr,len);		
			}
		}else{
			while(1){
				recvfrom(sockfd,&msg,LEN,0,(struct sockaddr *)&serveraddr,&len);
				puts(msg.text);
			}
		}
}
























